#include <string>
#include <cctype>
#include <climits>

using namespace std;

class Solution
{
public:
    int myAtoi(string s)
    {
        long long ans = 0;
        int i = 0;
        bool flag = false;
        while (s[i] == ' ')
        {
            i++;
        }

        if (s[i] == '-')
        {
            i++;
            flag = true;
            if (!isdigit(s[i]))
            {
                return 0;
            }
        }

        if (s[i] == '+')
        {
            ++i;
            if (!isdigit(s[i]))
            {
                return 0;
            }
        }

        for (i; i < s.size() && isdigit(s[i]); ++i)
        {
            ans = ans * 10 + s[i] - '0';
            if (ans > INT_MAX)
            {
                break;
            }
        }

        if (flag)
        {
            ans = -ans;
        }

        if (ans > INT_MAX)
        {
            ans = INT_MAX;
        }

        if (ans < INT_MIN)
        {
            ans = INT_MIN;
        }
        return ans;
    }
};